package yagwl.client.widget.internal;

import java.util.ArrayList;
import java.util.List;

import yagwl.client.widget.Spacer;

import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HasVerticalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;

public class Sorter extends Composite {
  private final HorizontalPanel rootHP = new HorizontalPanel();
  private final ListBox sortOrderLB = new ListBox();
  private final List<SortOrderOption> sortOrderOptions = new ArrayList<SortOrderOption>();
  private int sortOrderOptionIndex = 0;

  public Sorter() {
    initWidget(rootHP);
  }

  public void renderUI(final SortOrderChangeHandler sortOrderChangeHandler) {
    if (sortOrderOptionIndex >= sortOrderOptions.size())
      sortOrderOptionIndex = 0;
    if (sortOrderOptions.size() == 1)
      return;

    for (SortOrderOption option : sortOrderOptions) {
      sortOrderLB.addItem(option.label);
    }
    sortOrderLB.setSelectedIndex(sortOrderOptionIndex);
    Label sortL = new Label("Sort: ");
    rootHP.add(sortL);
    rootHP.add(new Spacer(5, 1));
    rootHP.add(sortOrderLB);
    rootHP.setCellVerticalAlignment(sortL, HasVerticalAlignment.ALIGN_MIDDLE);
    sortOrderLB.addChangeHandler(new ChangeHandler() {
      public void onChange(ChangeEvent event) {
        sortOrderOptionIndex = sortOrderLB.getSelectedIndex();
        sortOrderChangeHandler.onChange();
      }
    });
  }

  public interface SortOrderChangeHandler {
    public void onChange();
  }

  /**
   * Add a sort order option
   * 
   * @param number
   *          sort order number defined at the server
   * @param label
   *          label that appears on list box
   */
  public void addSortOrderOption(int number, String label) {
    SortOrderOption t = new SortOrderOption();
    t.number = number;
    t.label = label;
    sortOrderOptions.add(t);
  }

  public void setSortOrderOptionIndex(int sortOrderOptionIndex) {
    if (sortOrderOptionIndex < 0)
      sortOrderOptionIndex = 0;
    this.sortOrderOptionIndex = sortOrderOptionIndex;
  }

  public int getSortOrderNumber() {
    return sortOrderOptions.get(sortOrderOptionIndex).number;
  }

  public boolean isRenderable() {
    return sortOrderOptions.size() > 1;
  }

  private class SortOrderOption {
    private int number;
    private String label;
  }

}
